/**
 * 准备函数
 */
var operateRight = new Object();
$(document).ready(function() {
	// 加载权限
	loadRight();
	
	// 加载表格
	queryApplication();
	
	// 绑定函数
	$("#queryButton").bind("click", function(){
		queryApplication();
	});
	$("#createButton").bind("click", showCreateApplicationDialog);
	$("#confirmCreateApplicationButton").bind("click", confirmCreateApplication);
	$("#confirmModifyApplicationButton").bind("click", confirmModifyApplication);
});

/**
 * 加载权限
 */
function loadRight() {
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
}

/**
 * 查询
 */
function queryApplication(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var name = $.trim($("#name").val());
	if (name != null && name != "") {
		data['name'] = name;
	}
	
	var starNum = $.trim($("#starNum").val());
	if (starNum != null && starNum != "") {
		data['starNum'] = starNum;
	}
	
	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);

	// 调用接口
	var response = callInterface("post", "saas/application/queryApplication", data, false);
	if (response.code == 0) {
		// 清空分页
		$("#pageDiv").html("");

		
		var count = response.data.totalCount;
		var list = response.data.list;
		if (list != null && list.length > 0) {
			var materialSpan = "";
			for ( var i in list) {
				var url = list[i].images + Global.IMG_SiZE_TWO_H;
				materialSpan += '<div class="applicationItem">';
				materialSpan += '<dl class="clearfix">';
				materialSpan += '<dt class="fl" onclick="showApplicationDetailDialog(\'' + list[i].id + '\',\'' + list[i].name + '\');">';
				materialSpan += '<img src="' + url + '" />';
				materialSpan += '</dt>';
				materialSpan += '<dd class="fl">';
				materialSpan += '<h3>【'+list[i].name+'】<span class="star">';
				for(var k=0;k<list[i].starNum;k++){
					materialSpan += '<i class="icon-star"></i>'
				}
				materialSpan += '</span></h3><p class="describe" title="'+list[i].description+'">' + list[i].description + '</p>';
				materialSpan += '<p class="userNum">使用量：' + list[i].buyCount + '</p>';
				materialSpan += '<a href="javascript:void(0);" onclick="showModifyApplicationDialog(\'' + list[i].id + '\');">编辑</a>';
				materialSpan += '</h5></dd>';
				materialSpan += '</dl>';
				materialSpan += '</div>';
			}
			$('#applicationDiv').html(materialSpan);
			
			// 调用分页
			layui.use(['laypage'], function() {
				var laypage = layui.laypage;
				laypage.render({
					elem : 'pageDiv',
					// pages : pages,
					curr : pageIndex || 1, // 当前页
					count : count,
					limit : pageSize,
					skip : true, // 是否开启跳页
					layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
					groups : 5, // 连续显示分页数
					jump : function(obj, first) { // 触发分页后的回调
						if (!first) {
							queryApplication(obj.curr, obj.limit);
						}
					}
				});
			});
		}else{
			$('#applicationDiv').html("无应用!");
		}
	}
}

/**
 * 显示上传素材对话框
 */
function showCreateApplicationDialog() {
	$("#createApplicationDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#createApplicationForm')[0].reset();
	
	// 初始化文件选择相关
	$("#cMatPreUrl,#cStarNum").val("");
	var objPre = document.getElementById('cApplicationPreviewFile'); 
	objPre.outerHTML = objPre.outerHTML;
	$("#cFileDivListPre").html("");
	updateLayuiForm();
}

/**
 * 确认上传素材
 */
function confirmCreateApplication() {
	
	var data = {};
    var name = $("#cName").val();
    if(Utils.isNotNull(name)){
    	data.name = name;
    }else{
    	showAlert("请选择应用名称!");
		return false;
    }
    
    var icon = $("#cIcon").val();
    if(Utils.isNotNull(icon)){
    	data.icon = icon;
    }else{
    	showAlert("请选择应用图标!");
		return false;
    }
    
    var href = $("#cHref").val();
    if(Utils.isNotNull(href)){
    	data.href = href;
    }else{
    	showAlert("请选择应用链接!");
		return false;
    }
    
    var starNum = $("#cStarNum").val();
    if(Utils.isNotNull(starNum)){
    	data.starNum = starNum;
    }else{
    	showAlert("请选择应用星级!");
		return false;
    }
    
    var images = $("#cAppPreUrl").val();
	if(Utils.isNotNull(images)){
		data.images = images;
    }else{
    	showAlert("请上传应用预览图!");
		return false;
    }
	
	var description = $("#cDescription").val();
    if(Utils.isNotNull(description)){
    	data.description = description;
    }else{
    	showAlert("请选择应用简介!");
		return false;
    }
    
    // 调用接口
	var response = callInterface("post", "saas/application/createApplication", data,
			false);
	if (response.code == 0) {
		showMsg('操作成功!');
		// 关闭对话框
		$('#createApplicationDialog').modal("hide");
		queryApplication();
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 触发选择文件事件
 * 
 * @param selectFileId
 */
function doContTriggerClick(selectFileId){
	$("#"+selectFileId).trigger("click");
}

/**
 * 上传素材图片并预览 
 * inputFileId	:	图片文件 
 * fileShowDiv	:	图片预览 
 * fileType	:	文件类型(1:图片 2:视频 3:音频 4:网页 5:其他)
 */
var fuIndex = 0;
function selectFileToOss(inputFileId, fileShowDiv, isEdit) {
	
	var materialType = FileType.IMAGE_V;
	//文件种类
	var suppotFormat = getFileSuffix(materialType);
	//校验文件合法性
	var fileObjs = document.getElementById(inputFileId).files[0];
	var fileName = fileObjs.name;
	//转换大小写
	var suffix = (fileName.substring(fileName.lastIndexOf(".")+1,fileName.length)).toLowerCase(); 
	if (suppotFormat.indexOf(suffix) == -1) {
		Utils.showCustomTips(inputFileId, 1, '文件格式错误，支持的格式为：' + suppotFormat, '#000', '#ffe74c', 5);
		fileObjs.outerHTML = fileObjs.outerHTML; 
		return false;
	}
	
	var isOk = checkUploadFileSize(FileType.IMAGE_PRE_V, getFileSizeMByB(fileObjs.size))
	if(!isOk){
		Utils.showCustomTips(inputFileId, 1, "预览图文件超出限制大小，应≤" + FileType.IMAGE_PRE_MAX_SIZE + "M", '#000', '#ffe74c', 5);
		return false;
	}
	
	// 图片
	createLoadingDiv();
	fuIndex++;
	// 初始化、进度条(默认隐藏)、文件名
	var fileDiv = "";
    fileDiv += "	<div class='fileItem file-item fl materialType_"+fuIndex+"' data-index='"+fuIndex+"' data-type='" + fuIndex + "'>";
    fileDiv += "		<div class='item-img'>";
    fileDiv += "			<img class='materialUrl_"+fuIndex+"' src=\"image/fileLogo/"+suffix+".jpg\" />";
    fileDiv += "		</div>";
    fileDiv += "		<div class='progress'>";
    fileDiv += "			<div class='solidBar fileProgress_"+fuIndex+"' style='width:100%' ></div>";
    fileDiv += "			<div class='progressTit fileProgressTit_"+fuIndex+"'>待上传...</div>";
    fileDiv += "		</div>";
    fileDiv += "	</div>";
    $("#"+fileShowDiv).html(fileDiv);
    
    // 获取请求参数
	var client = getOssWrapper();
	// 执行请求
	client.multipartUpload(getStoreAs(fileObjs), fileObjs,{
		progress: function* (percent, cpt) {  
			percent =  Utils.toFormatDecimal(percent*100,0);
			setFileProgress(percent, fuIndex);
		}
	}).then(function (result) {
		var fileUrl = handleOssUrl(result.res.requestUrls[0]);
		if(isEdit){
			$("#mAppPreUrl").val(fileUrl);
		}else{
			$("#cAppPreUrl").val(fileUrl);
		}
		$(".materialUrl_"+fuIndex).attr("src",fileUrl);
		closeLoadingDiv();
	}).catch(function (err) {
		closeLoadingDiv();
	});
}

/**
 * 显示修改对话框
 */
function showModifyApplicationDialog(id) {
	// 显示对话框
	$("#modifyApplicationDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyApplicationForm')[0].reset();
	
	// 查询素材详情
	getApplicationDetail(id);
}

function getApplicationDetail(id){
	// 调用接口
	var response = callInterface("post", "saas/application/getApplication", {
		'id' : id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		$("#mId").val(data.id);
		$("#mName").val(data.name);
		$("#mIcon").val(data.icon);
		$("#mHref").val(data.href);
		$("#mStarNum").val(data.starNum);
		$("#mDescription").val(data.description);
		$("#mAppPreUrl").val(data.images);
		
		fuIndex++;
		// 初始化、进度条(默认隐藏)、文件名
		var fileDiv = "";
	    fileDiv += "	<div class='fileItem file-item fl materialType_"+fuIndex+"' data-index='"+fuIndex+"' data-type='" + fuIndex + "'>";
	    fileDiv += "		<div class='item-img'>";
	    fileDiv += "			<img class='materialUrl_"+fuIndex+"' src=\""+data.images+"\" />";
	    fileDiv += "		</div>";
	    fileDiv += "	</div>";
	    $("#mFileDivListPre").html(fileDiv);
		updateLayuiForm();
	} else {
		showErrorMsg(response.code, response.message);
	}
}


/**
 * 确认编辑素材
 */
function confirmModifyApplication() {
	
	var data = {};
	data.id = $("#mId").val();
    var name = $("#mName").val();
    if(Utils.isNotNull(name)){
    	data.name = name;
    }else{
    	showAlert("请选择应用名称!");
		return false;
    }
    
    var icon = $("#mIcon").val();
    if(Utils.isNotNull(icon)){
    	data.icon = icon;
    }else{
    	showAlert("请选择应用图标!");
		return false;
    }
    
    var href = $("#mHref").val();
    if(Utils.isNotNull(href)){
    	data.href = href;
    }else{
    	showAlert("请选择应用链接!");
		return false;
    }
    
    var starNum = $("#mStarNum").val();
    if(Utils.isNotNull(starNum)){
    	data.starNum = starNum;
    }else{
    	showAlert("请选择应用星级!");
		return false;
    }
    
    var images = $("#mAppPreUrl").val();
	if(Utils.isNotNull(images)){
		data.images = images;
    }else{
    	showAlert("请上传应用预览图!");
		return false;
    }
	
	var description = $("#mDescription").val();
    if(Utils.isNotNull(description)){
    	data.description = description;
    }else{
    	showAlert("请选择应用简介!");
		return false;
    }
    
    // 调用接口
	var response = callInterface("post", "saas/application/modifyApplication", data,
			false);
	if (response.code == 0) {
		showMsg('操作成功!');
		// 关闭对话框
		$('#modifyApplicationDialog').modal("hide");
		queryApplication();
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 删除
 */
function delApplication(id) {
	// 询问框
	layer.confirm('确定删除该应用吗？', {
	  offset :'20px',btn: ['确定','取消'] //按钮
	}, function(){
		// 调用接口
		var response = callInterface("post", "saas/application/deleteApplication", {"id" : id} , false);
		if (response.code == 0) {
			showMsg('操作成功!');

			// 刷新
			queryApplication(currPage);
		} else {
			showErrorMsg(response.code, response.message);
		}
	}, function(){
		return;
	});
}